package com.kelvin.paopao.module.main;

import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.kelvin.paopao.R;
import com.kelvin.paopao.adapter.MainViewPagerAdapter;
import com.kelvin.paopao.easemob.EaseMobHelper;
import com.kelvin.paopao.injector.components.DaggerMainComponent;
import com.kelvin.paopao.injector.modules.MainModule;
import com.kelvin.paopao.module.base.BaseActivity;
import com.kelvin.paopao.module.main.My.MainMyFragment;
import com.kelvin.paopao.module.main.date.datemain.MainDateFragment;
import com.kelvin.paopao.module.main.find.find.MainFindFragment;
import com.kelvin.paopao.rxbus.Subscribe;
import com.kelvin.paopao.rxbus.ThreadMode;
import com.kelvin.paopao.rxbus.event.ChatEvent;
import com.kelvin.paopao.utils.Constant;
import com.kelvin.paopao.utils.LoginUtil;
import com.kelvin.paopao.widgets.NoScrollViewPager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class MainActivity extends BaseActivity<MainPresenter> {
    @BindView(R.id.viewPager)
    NoScrollViewPager viewPager;
    @BindView(R.id.rb_find)
    RadioButton rbFind;
    @BindView(R.id.rb_date)
    RadioButton rbDate;
    @BindView(R.id.rb_me)
    RadioButton rbMe;
    @BindView(R.id.rg_tab)
    RadioGroup rgTab;
    @BindView(R.id.ll_menu_bottom)
    LinearLayout llMenuBottom;
    @BindView(R.id.image_middle_menu_image)
    ImageView imageMiddleMenuImage;
    @BindView(R.id.tv_middle_menu_text)
    TextView tvMiddleMenuText;
    @BindView(R.id.tv_unread)
    TextView tvUnread;

    private MainViewPagerAdapter adapter;
    private MainDateFragment mainDateFragment;
    private MainFindFragment mainFindFragment;
    private MainMyFragment mainMyFragment;

    private boolean isBackground = true;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_main;
    }

    @Override
    protected void initInjector() {
        DaggerMainComponent.builder().applicationComponent(getAppComponent())
                .mainModule(new MainModule(this)).build().inject(this);
    }


    @Override
    protected void onResume() {
        super.onResume();
        //这里需要特别注意的，当这个界面进入后台的时候要解除这个监听还有移除这个activity，
        // 因为这个时候全局的监听器会起作用
        EaseMobHelper easeMobHelper = EaseMobHelper.getInstance();
        easeMobHelper.pushActivity(this);

        //注册rxbus
        mPresenter.registerRxBus();

        if (isBackground == true) {
            refreshUIWithMessage();
            //刷新地理位置
            isBackground = false;
        }

    }

    @Override
    protected void onPause() {
        super.onPause();
        //注销rxbus
        mPresenter.unregisterRxBus();

        isBackground = true;
        EaseMobHelper easeMobHelper = EaseMobHelper.getInstance();
        easeMobHelper.popActivity(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageReceive(ChatEvent messageEvent) {
        if (messageEvent.chat_type == ChatEvent.SINGLE_CHAT) {
            refreshUIWithMessage();
        }
    }

    /**
     * 获取消息数量
     *
     * @return
     */
    public int getUnreadMsgCountTotal() {
        int unreadMsgCountTotal = 0;
        int chatroomUnreadMsgCount = 0;
        unreadMsgCountTotal = EMClient.getInstance().chatManager().getUnreadMsgsCount();
        for (EMConversation conversation : EMClient.getInstance().chatManager().getAllConversations().values()) {
            if (conversation.getType() == EMConversation.EMConversationType.ChatRoom)
                chatroomUnreadMsgCount = chatroomUnreadMsgCount + conversation.getUnreadMsgCount();
        }
        return unreadMsgCountTotal - chatroomUnreadMsgCount;
    }

    //更新未读信息的数量
    public void updateUnreadLabel() {

        int count = getUnreadMsgCountTotal();
        if (count == 0) {
            clearUnReadCount();
            if (mainMyFragment != null) {
                mainMyFragment.clearUnReadCount();
            }
        } else {
            if (count > 99) {
                setUnReadCount("99+");
                if (mainMyFragment != null) {
                    mainMyFragment.setUnReadCount("99+");
                }
            } else {
                setUnReadCount(String.valueOf(count));
                if (mainMyFragment != null) {
                    mainMyFragment.setUnReadCount(String.valueOf(count));
                }
            }
        }
    }

    /**
     * 刷新界面
     */
    private void refreshUIWithMessage() {
        updateUnreadLabel();
    }

    @Override
    protected void initViews() {
        //判断是否登陆
        Constant.IS_LOGIN = EaseMobHelper.getInstance().isLoggedIn();

        mainDateFragment = new MainDateFragment();
        mainFindFragment = new MainFindFragment();
        mainMyFragment = new MainMyFragment();
        List<Fragment> fragmentList = new ArrayList<>();
        fragmentList.add(mainFindFragment);
        fragmentList.add(mainDateFragment);
        fragmentList.add(mainMyFragment);

        adapter = new MainViewPagerAdapter(getSupportFragmentManager(), fragmentList);
        viewPager.setAdapter(adapter);
        viewPager.setOffscreenPageLimit(2);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                switch (position) {
                    case 0:
                        rbFind.setChecked(true);
                        switchMiddleMenuNormal();
                        break;
                    case 2:
                        rbMe.setChecked(true);
                        switchMiddleMenuNormal();
                        LoginUtil.checkLogin(MainActivity.this);
                        break;
                    case 1:
                        rgTab.clearCheck();
                        switchMiddleMenuCheck();
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        rgTab.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == rbFind.getId()) {
                    viewPager.setCurrentItem(0);
                } else if (checkedId == rbMe.getId()) {
                    viewPager.setCurrentItem(2);
                }
            }
        });

    }

    @Override
    protected void updateViews(boolean isRefresh) {

    }

    /**
     * 邀约未选中
     */
    private void switchMiddleMenuNormal() {
        imageMiddleMenuImage.setImageResource(R.mipmap.main_tab_trade_normal_big);
        tvMiddleMenuText.setTextColor(getResources().getColor(R.color.main_menu_color_normal));
    }

    /**
     * 邀约选中
     */
    private void switchMiddleMenuCheck() {
        imageMiddleMenuImage.setImageResource(R.mipmap.main_tab_trade_selected_big);
        tvMiddleMenuText.setTextColor(getResources().getColor(R.color.main_menu_color_check));
    }


    @OnClick({R.id.image_middle_menu_image, R.id.tv_middle_menu_text})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.image_middle_menu_image:
                rgTab.clearCheck();
                switchMiddleMenuCheck();
                viewPager.setCurrentItem(1);
                break;
            case R.id.tv_middle_menu_text:
                rgTab.clearCheck();
                switchMiddleMenuCheck();
                viewPager.setCurrentItem(1);
                break;
        }
    }

    /**
     * 设置未读个数
     */
    private void setUnReadCount(String count) {
        tvUnread.setVisibility(View.VISIBLE);
        tvUnread.setText(count);
    }

    /**
     * 设置未读个数
     */
    private void clearUnReadCount() {
        if (tvUnread != null) {
            tvUnread.setVisibility(View.GONE);
        }
    }

    private long currentTime;

    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - currentTime > 2000) {
            Toast.makeText(MainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            currentTime = System.currentTimeMillis();
        } else {
            finish();
        }
    }
}
